import pymysql
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import make_response, request
from flask_cors import CORS

pymysql.install_as_MySQLdb()

app = Flask(__name__)
# ------------------database----------------------------
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@localhost:3306/waibao'
# 指定数据库文件
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

# 允许修改跟踪数据库
db = SQLAlchemy(app)


class Admin(db.Model):
    id = db.Column(db.Integer, primary_key=True, comment='唯一id')
    account = db.Column(db.String(10), nullable=False, comment='账号')
    password = db.Column(db.String(15), nullable=False, comment='密码')
    rid = db.Column(db.String(120), nullable=False, comment='账号等级')
    createTime = db.Column(db.String(120), nullable=False, comment='创建时间')
    describe = db.Column(db.String(120), nullable=False, comment='描述')
    status = db.Column(db.String(120), nullable=False, comment='状态')

# 增加数据
def addadmin(account, password, rid, createTime, describe, status='正常'):
    # 处理传入的元组参数
    if isinstance(account, tuple):
        account = account[0]
    if isinstance(password, tuple):
        password = password[0]
    if isinstance(rid, tuple):
        rid = rid[0]
    if isinstance(createTime, tuple):
        createTime = createTime[0]
    if isinstance(describe, tuple):
        describe = describe[0]
    
    admin = Admin(account=account, password=password, rid=rid, createTime=createTime, describe=describe, status=status)
    db.session.add_all([admin])
    db.session.commit()


# 查询所有
def getalladmin():
    admin_list = []
    admins = Admin.query.all()
    # 类似于 select * from Books

    for s in admins:
        dic = {}
        dic['id'] = s.id
        dic['account'] = s.account
        dic['password'] = s.password
        dic['rid'] = s.rid
        dic['createTime'] = s.createTime
        dic['describe'] = s.describe
        dic['status'] = s.status
        admin_list.append(dic)
    return admin_list


# 通过id查询
def findadminbyid(id):
    admin = Admin.query.get(id)
    if not admin:
        return False
    dic = {}
    dic['id'] = admin.id
    dic['account'] = admin.account
    dic['password'] = admin.password
    dic['rid'] = admin.rid
    dic['createTime'] = admin.createTime
    dic['describe'] = admin.describe
    dic['status'] = admin.status
    return dic


# 通过id删除数据
def deleteadmin(id):
    delete_id = Admin.query.get(id)
    if not delete_id:
        return False
    db.session.delete(delete_id)
    db.session.commit()


# 修改数据
def updateadmin(id, account='', password='', rid='', createTime='', describe='', status=''):
    admin = Admin.query.get(id)
    if not admin:
        return False
    
    if not account == '':
        admin.account = account
    if not password == '':
        admin.password = password
    if not rid == '':
        admin.rid = rid
    if not createTime == '':
        admin.createTime = createTime
    if not describe == '':
        admin.describe = describe
    if not status == '':
        admin.status = status

    db.session.commit()
    return True


# 解决浏览器浏览器访问输出乱码问题
app.config['JSON_AS_ASCII'] = False


@app.after_request
def after(resp):
    resp = make_response(resp)
    resp.headers['Access-Control-Allow-Origin'] = '*'  # 允许跨域地址
    resp.headers['Access-Control-Allow-Methods'] = '*'  # 请求 '*' 就是全部
    resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'  # 头部
    resp.headers['Access-Control-Allow-Credentials'] = 'True'
    return resp


CORS(app, resources=r'/*', supports_credentials=True)


# 前端通过传参增加admin
@app.route('/addadmin', methods=['POST'])
def add():
    response_object = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.get_json()
        print('调用add方传过来的参数是', post_data)
        admin_list = getalladmin()
        account_list=[]
        for i in range(len(admin_list)):
            account_list.append(admin_list[i]['account'])
        if post_data.get('account') in account_list:
            response_object['message'] = '用户名重复!'
            response_object["status"] = 'fail'
            return response_object
        if post_data.get('account') is None:
            response_object['message'] = '用户名是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        if post_data.get('password') is None:
            response_object['message'] = '密码是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        if post_data.get('rid') is None:
            response_object['message'] = '用户等级是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        if post_data.get('createTime') is None:
            response_object['message'] = '创建时间是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        if post_data.get('describe') is None:
            response_object['message'] = '用户描述是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        
        account = str(post_data.get('account')).strip()
        password = str(post_data.get('password')).strip()
        rid = str(post_data.get('rid')).strip()
        createTime = str(post_data.get('createTime')).strip()
        describe = str(post_data.get('describe')).strip()
        status = str(post_data.get('status', '正常')).strip()

        if account is None or account == '':
            response_object['message'] = '账号不能为空!'
            response_object["status"] = 'fail'
            return response_object
        if password is None or password == '':
            response_object['message'] = '密码不能为空!'
            response_object["status"] = 'fail'
            return response_object
        if rid is None or rid == '':
            response_object['message'] = '用户等级不能为空'
            response_object["status"] = 'fail'
            return response_object
        if createTime is None or createTime == '':
            response_object['message'] = '创建时间不能为空!'
            response_object["status"] = 'fail'
            return response_object
        if describe is None or describe == '':
            response_object['message'] = '用户描述不能为空'
            response_object["status"] = 'fail'
            return response_object
        
        addadmin(account, password, rid, createTime, describe, status)
        response_object['message'] = '添加成功!'
    return response_object


# 前端通过传id删除
@app.route('/deleteadmin', methods=['DELETE'])
def delete():
    response_object = {'status': 'success'}
    if request.method == 'DELETE':
        post_data = request.get_json()
        print('调用delete方传过来的参数是：', post_data)
        if post_data.get('id') is None:
            response_object['message'] = 'id是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        id = post_data.get('id')
        result = deleteadmin(id)
        if result is False:
            response_object['message'] = '需要删除的数据不存在!'
            response_object["status"] = 'fail'
            return response_object
        else:
            response_object['message'] = '用户已删除!'
            return response_object


# 前端通过传参修改
@app.route('/updateadmin', methods=['POST'])
def update():
    response_object = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.get_json()
        print('调用update方传过来的参数是', post_data)
        
        if post_data.get('id') is None:
            response_object['message'] = 'id是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        
        if post_data.get('account') is None:
            response_object['message'] = '用户名是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        if post_data.get('password') is None:
            response_object['message'] = '密码是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        if post_data.get('rid') is None:
            response_object['message'] = '用户等级是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        if post_data.get('createTime') is None:
            response_object['message'] = '创建时间是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        if post_data.get('describe') is None:
            response_object['message'] = '用户描述是必传参数!'
            response_object["status"] = 'fail'
            return response_object
        
        id = post_data.get('id')
        # 验证ID是否存在
        admin = Admin.query.get(id)
        if not admin:
            response_object['message'] = '需要修改的id不存在!'
            response_object["status"] = 'fail'
            return response_object
        
        account = str(post_data.get('account')).strip()
        password = str(post_data.get('password')).strip()
        rid = str(post_data.get('rid')).strip()
        createTime = str(post_data.get('createTime')).strip()
        describe = str(post_data.get('describe')).strip()
        status = str(post_data.get('status', '正常')).strip()

        if account is None or account == '':
            response_object['message'] = '账号不能为空!'
            response_object["status"] = 'fail'
            return response_object
        if password is None or password == '':
            response_object['message'] = '密码不能为空!'
            response_object["status"] = 'fail'
            return response_object
        if rid is None or rid == '':
            response_object['message'] = '用户等级不能为空'
            response_object["status"] = 'fail'
            return response_object
        if createTime is None or createTime == '':
            response_object['message'] = '创建时间不能为空!'
            response_object["status"] = 'fail'
            return response_object
        if describe is None or describe == '':
            response_object['message'] = '用户描述不能为空'
            response_object["status"] = 'fail'
            return response_object

        result = updateadmin(id=id, account=account, password=password, rid=rid, createTime=createTime, describe=describe, status=status)
        if result:
            response_object['message'] = '已更新!'
        else:
            response_object['message'] = '更新失败!'
            response_object["status"] = 'fail'
        return response_object


# 前端通过不传参默认查询所有书籍，传id查询对应书籍
@app.route('/query', methods=['GET'])  # 将请求方式更改为GET
def query():
    response_object = {'status': 'success'}
    id = request.args.get('id')  # 通过查询字符串获取'id'参数
    if id is None:  # 如果未传入'id'参数则返回所有书籍
        admins = getalladmin()
        response_object['message'] = '查询所有admin成功!'
        response_object['admins'] = admins
        return response_object

    id = id.strip()
    if id == '':
        response_object['message'] = 'id不能为空!'
        response_object['status'] = 'fail'
        return response_object

    admin = findadminbyid(id)
    if admin is False:
        response_object['message'] = '需要查询的admin不存在!'
        response_object['status'] = 'fail'
        return response_object
    else:
        response_object['message'] = '查询成功!'
        response_object['admin'] = admin
        return response_object


if __name__ == '__main__':
    # 默认是5000，这里设置5001避免本地冲突。打开debug方便调试
    app.run(debug=True, port=5001)